<link rel="stylesheet" href="<%=resource%>/css/common.css">
<% local dsp=require "luci.dispatcher" -%>

<script type="text/javascript" src="<%=resource%>/echarts.min.js?v=5.0"></script>

	<script type="text/javascript">//<![CDATA[
		let visit_time_data = []; 
		let user_list_data = {
			list: [
				
			]
		}
		let cur_page = 0;

		function getAllUsersData(page) {
			new XHR().get('<%=url('admin/network/get_all_users')%>', {flag: 3, page: page},
				function (x, data) {
					user_list_data = data.data
					render_user_list(user_list_data);
				}
			);
		}

		window.onload = function() {
			cur_page = 0; // default fetch all
			getAllUsersData(cur_page);

			setInterval(function() {
				getAllUsersData(cur_page);
			}, 3000);
		}

		function showSuccessMessage(message = '<%:Settings saved successfully%>') {
			const modal = document.getElementById('modal');
			const messageElement = modal.querySelector('p');
			messageElement.textContent = message;
			modal.style.display = 'flex';
			setTimeout(() => {
				modal.style.display = 'none';
			}, 1000);
		}

		function render_user_list(data) {
			var tb = document.getElementById('user_status_table');
			var user_list = data.list;
			if (user_list && tb) {
				while (tb.rows.length > 1)
					tb.deleteRow(1);
				for (var i = 0; i < user_list.length; i++) {
					var nickname = user_list[i].nickname || "";
					var hostname = user_list[i].hostname || "";
					var displayName = nickname || hostname || "--";

					var tr = tb.insertRow(-1);
					tr.className = 'tr';
					if (user_list[i].online != 1) {
						tr.style.color = '#A9A9A9'; 
					}
					tr.insertCell(-1).innerHTML = `
						<div style="display: flex; align-items: center;">
							<div>
								<div>${displayName}</div>
								<div>${user_list[i].mac}</div>
							</div>
						</div>
					`;
					tr.insertCell(-1).innerHTML = user_list[i].ip;
					// lua api return {}
				     if (!Array.isArray(user_list[i].applist))           
                         user_list[i].applist = [] 
					var app_list_str = user_list[i].applist.map(app => {
						var iconSrc = app.icon === 0 ? '<%=resource%>/app_icons/default.png' : `<%=resource%>/app_icons/${app.id}.png`;
						return `<img src="${iconSrc}" alt="${app.name}" title="${app.name}" style="width: 20px; height: 20px; border-radius: 5px; margin-right: 8px;">`;
					}).join("") || "--";
					tr.insertCell(-1).innerHTML = app_list_str;
					var current_app = user_list[i].app || "--";
					tr.insertCell(-1).innerHTML = current_app;
					var current_url = user_list[i].url || "--";
					var display_url = current_url;
					if (current_url !== "--" && current_url.length > 20) {
						display_url = current_url.substring(0, 10) + "..." + current_url.substring(current_url.length - 10);
					}
					tr.insertCell(-1).innerHTML = `<span title="${current_url}">${display_url}</span>`;
					tr.insertCell(-1).innerHTML = user_list[i].online == 1 
						? `<span style="color: green;"><%:Online%></span>` 
						: "<%:Offline%>";
					tr.insertCell(-1).innerHTML = `
						<button type="button" class="cbi-button cbi-button-add" onclick="showDetails('${user_list[i].mac}')" style="margin-right: 5px;"><%:Details%></button>
						<button type="button" class="cbi-button cbi-button-add" onclick="showModifyNickname('${user_list[i].mac}')"><%:Remark%></button>
					`;

					
					var childs = tr.childNodes;
					Array.prototype.forEach.call(childs, function (child) {
						child.className = 'td';
					});
				}
			}
		}

		function render_visit_list_table(data) {
			var tb = document.getElementById('visit_list_table');
			var visit_list = data.list;
			if (visit_list && tb) {
				while (tb.rows.length > 1)
					tb.deleteRow(1);
				for (var i = 0; i < visit_list.length; i++) {
					var action_status = visit_list[i].act == 1 ? 
						'<span style="color: red;"><%:Filtered%></span>' : 
						'<span style="color: green;"><%:Unfiltered%></span>';
					var hostname = visit_list[i].hostname == "" || visit_list[i].hostname == "*" ? "--" : visit_list[i].hostname;
					var tr = tb.insertRow(-1);
					tr.className = 'tr';

					var iconSrc = visit_list[i].icon === 0 ? '<%=resource%>/app_icons/default.png' : `<%=resource%>/app_icons/${visit_list[i].id}.png`;
					tr.insertCell(-1).innerHTML = `
						<div style="height: 24px; display: flex; align-items: center;">
							<img src="${iconSrc}" alt="${visit_list[i].name}" title="${visit_list[i].name}" style="width: 20px; height: 20px; border-radius: 5px; margin-right: 4px;">
							<span>${visit_list[i].name}</span>
						</div>
					`;


					var first_time_date = new Date(visit_list[i].ft * 1000);
					var first_time_str = first_time_date.toLocaleString(); 

					var latest_time_date = new Date(visit_list[i].lt * 1000); 
					var latest_time_str = latest_time_date.toLocaleString(); 

					tr.insertCell(-1).innerHTML = first_time_str;
					tr.insertCell(-1).innerHTML = latest_time_str;
					var hour = parseInt(visit_list[i].tt / 3600);
					var seconds = visit_list[i].tt % 3600;
					var min = parseInt(seconds / 60)
					var total_time_str;
					if (visit_list[i].act == 1)
						total_time_str = "-"
					else {
						if (hour > 0)
							total_time_str = hour + "<%:h%>" + min + "<%:m%>"
						else {
							if (min == 0)
								min = 1;
							total_time_str = min + "<%:m%>"
						}
					}
					tr.insertCell(-1).innerHTML = total_time_str;
					tr.insertCell(-1).innerHTML = action_status;

					var childs = tr.childNodes;
					Array.prototype.forEach.call(childs, function (child) {
						child.className = 'td';
					});
				}
			}
		}

		function showDetails(mac) {
			var modal = document.getElementById('detailsModal');
			modal.style.display = 'flex';
			updateDeviceInfoTitle(mac);

			new XHR().get('<%=url('admin/network/dev_visit_time')%>/' + mac, null,
				function (x, st) {
					visit_time_data = st;
					display_app_visit_view(visit_time_data);
				}
			);

			new XHR().get('<%=url('admin/network/dev_visit_list')%>/' + mac, null,
				function (x, st) {
					visit_list_data = st;
					render_visit_list_table(visit_list_data);
				}
			);
		}

		function updateDeviceInfoTitle(mac) {
			var deviceInfo = '(' + mac + ')';
			
			if (user_list_data && user_list_data.list) {
				var device = user_list_data.list.find(function(user) {
					return user.mac === mac;
				});
				
				if (device) {
					if (device.nickname && device.nickname.trim() !== '') {
						deviceInfo = '(' + device.nickname + ')';
					} else if (device.hostname && device.hostname.trim() !== '') {
						deviceInfo = '(' + device.hostname + ')';
					}
				}
			}
			
			document.getElementById('deviceInfo').textContent = deviceInfo;
		}

		function showModifyNickname(mac) {
			var modal = document.getElementById('nicknameModal');
			modal.style.display = 'flex';
			document.getElementById('nicknameMac').value = mac;
			document.getElementById('nicknameMacDisplay').textContent = mac;
			document.getElementById('nicknameInput').value = '';
		}

		function validateNickname(nickname) {
			const invalidChars = /[\s'"]/;
			return !invalidChars.test(nickname) && nickname.length <= 32;
		}

		function submitNicknameChange() {
			var mac = document.getElementById('nicknameMac').value;
			var nickname = document.getElementById('nicknameInput').value;

			if (!validateNickname(nickname)) {
				alert('<%:Please enter a valid remark%>');
				return;
			}

			new XHR().post('<%=url('admin/network/set_nickname')%>', 
			{ mac: mac, nickname: nickname },
			function(x, data) {
				console.log('Nickname updated successfully');
				closeModal('nicknameModal');
				showSuccessMessage('<%:Settings saved successfully%>');
				getAllUsersData(cur_page);
			});
		}

		function closeModal(modalId) {
			var modal = document.getElementById(modalId);
			if (modal) {
				modal.style.display = 'none';
			}
		}

		function showTabContent(tabId) {
			var tabs = document.querySelectorAll('.tab-body');
			var tabItems = document.querySelectorAll('.tab-item');

			tabs.forEach(function(tab) {
				tab.classList.remove('active');
			});

			tabItems.forEach(function(item) {
				item.classList.remove('active');
			});

			document.getElementById(tabId).classList.add('active');
			document.querySelector('.tab-item[onclick="showTabContent(\'' + tabId + '\')"]').classList.add('active');
		}

    function get_display_time(total_time) {
        var hour = parseInt(total_time / 3600);
        var seconds = total_time % 3600;
        var min = parseInt(seconds / 60)
        var seconds2 = seconds % 60;
        var total_time_str;

        if (hour > 0)
            total_time_str = hour + "<%:h%>" + min + "<%:m%>"
        else {
            if (min == 0 && seconds2 != 0)
                min = 1;
            total_time_str = min + "<%:m%>"
        }
        return total_time_str;
    }

    function display_app_visit_view(data) {
        var chartElement = document.getElementById('app_time_chart');
        if (!chartElement) {
            console.error("Chart element not found");
            return;
        }
        var myChart = echarts.init(chartElement);
        if (!data) {
            return;
        }
		var total_time = 0
		var app_stat_array = new Array();
		if (data.length == 0){
			var app_obj ={}
			app_obj.name = "<%:Unknown App%>"
			app_obj.value = 0
			app_obj.legendname = app_obj.name
			app_stat_array.push(app_obj)
		}
		else{
			for (var i = 0; i < data.length; i++) {
				var app_obj = {};
				app_obj.value = data[i].t;
				app_obj.legendname = data[i].name;
				var tmp_time = get_display_time(data[i].t);
				app_obj.name = data[i].name + "  " + tmp_time;
				total_time += data[i].t
				app_stat_array.push(app_obj);
			}
		}
        var total_time_str = get_display_time(total_time);
        var option = {
			grid:{
			},
            title: [
                {
                    text: "<%:App Time Statistics%>",
                    textStyle: {
                        fontSize: 16,
                        color: "black"
                    },
                    left: "2%"
                },
                {
                    text: '',
                    subtext: total_time_str,
                    textStyle: {
                        fontSize: 15,
                        color: "black"
                    },
                    subtextStyle: {
                        fontSize: 15,
                        color: 'black'
                    },
                    textAlign: "center",
                    x: '34.5%',
                    y: '44%',
                }],
            tooltip: {
                trigger: 'item',
                formatter: function (parms) {
                    var total_time = get_display_time(parms.data.value);
                    var str = parms.seriesName + "</br>" +
                        parms.marker + "" + parms.data.legendname + "</br>" +
                        "<%:Visit Time%>: " + total_time + "</br>" +
                        "<%:Percentage%>: " + parms.percent + "%";
                    return str;
                }
            },
            legend: {
                type: "scroll",
                orient: 'vertical',
                left: '75%',
                align: 'left',
                top: 'middle',
                textStyle: {
                    color: '#8C8C8C'
                },
                height: 250
            },
            series: [
                {
                    name: "<%:Visit Time%>",
                    type: 'pie',
                    radius: ['58%', '70%'],
                    center: ['35%', '50%'], 
                    clockwise: false,
                    avoidLabelOverlap: true,
                    itemStyle: {
                        borderRadius: 1,
                        borderColor: "#fff",
                        borderWidth: 1,
                    },
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: '{b}: {c} ({d}%)',
                        normal: {
                            show: true,
                            position: 'outter',
                            formatter: function (parms) {
                                return parms.data.legendname
                            }
                        }
                    },
                    labelLine: {
                        show: true,
                        length: 8,
                        length2: 7,
                        smooth: true,
                    },
                    data: app_stat_array
                }
            ]
        };

        myChart.setOption(option);
    }

//]]></script>

<div style="max-height: 750px; overflow-y: auto;padding-right: 20px;"> <!-- Added container with fixed height and overflow -->

	<div class="cbi-section cbi-tblsection">

		<div>

		<table class="table cbi-section-table" id="user_status_table" style="table-layout: fixed; width: 100%;">
			<tr class="tr">
				<th class="th" style="width: 85px;">
					<%:Device Info%>
				</th>
				<th class="th" style="width: 80px;">
					<%:IP Address%>
				</th>
				<th class="th" style="width: 110px;">
					<%:Common App(TOP5)%>
				</th>
				<th class="th" style="width: 65px;">
					<%:Active App%>
				</th>
				<th class="th" style="width: 110px;">
					<%:Current URL%>
				</th>
				<th class="th" style="width: 55px;">
					<%:Online Status%>
				</th>
				<th class="th" style="width: 120px;">
					<%:Actions%>
				</th>
			</tr>
			<tr class="tr">
				<td class="td" colspan="9"><em><br />
						<%:Collecting data...%>
					</em></td>
			</tr>
		</table>

		</div>
	</div>
</div>
<!-- Details Modal -->
<div id="detailsModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
    <div style="background-color: white; padding: 30px; border-radius: 8px; text-align: left; width: 800px; height: 550px; display: flex; flex-direction: column; position: relative; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);">
        <button type="button" onclick="closeModal('detailsModal')" style="position: absolute; top: 15px; right: 15px; background-color: transparent; border: none; font-size: 24px; color: #666; cursor: pointer; width: 30px; height: 30px; border-radius: 50%; transition: background-color 0.2s;">&times;</button>
        <h4 style="margin: 0 0 25px 0; color: #333; font-size: 18px;"><%:Device Details%> <span id="deviceInfo" style="color: #666; font-size: 14px; font-weight: normal;"></span></h4>
        
        <!-- Tab List -->
        <ul class="tab-list">
            <!-- <li class="tab-item onclick="showTabContent('tab1')">基本信息</li> -->
            <li class="tab-item active" onclick="showTabContent('tab2')"><%:App Statistics%></li>
			<li class="tab-item" onclick="showTabContent('tab3')"><%:Access Records%></li>
        </ul>

        <!-- <div id="tab1" class="tab-body" >

			<div class="info-container">
				<div class="info-row">
					<div class="info-column">
						<p><span class="field-label">MAC地址:</span> <span class="field-value" id="device_mac">--</span></p>
						<p><span class="field-label">在线状态:</span> <span class="field-value" id="device_ip">--</span></p>
						<p><span class="field-label">在线/离线时间:</span> <span class="field-value" id="download_total">--</span></p>
						<p><span class="field-label">在线APP:</span> <span class="field-value" id="download_total">--</span></p>
					</div>
					<div class="info-column">
						<p><span class="field-label">IP地址:</span> <span class="field-value" id="group">--</span></p>
						<p><span class="field-label">主机名:</span> <span class="field-value" id="group">--</span></p>
						<p><span class="field-label">备注:</span> <span class="field-value" id="hostname">--</span></p>
					</div>
				</div>
			</div>
        </div> -->
        <div id="tab2" class="tab-body active">
			<div class="pie-chart">
				<div id="app_time_chart" style="width:100%;height: 350px;">
				</div>
			</div>
        </div>

		<div id="tab3" class="tab-body">
			<div style="max-height: 350px; overflow-y: auto;padding-right: 20px;"> <!-- Added container with fixed height and overflow -->
				<table class="table cbi-section-table" id="visit_list_table">
					<tr class="tr table-titles">
						<th class="th">
							<%:App Name%>
						</th>
			
						<th class="th">
							<%:Start Time%>
						</th>

						<th class="th">
							<%:Last Time%>
						</th>
						<th class="th">
							<%:Duration%>
						</th>
						<th class="th">
							<%:Filter Status%>
						</th>
					</tr>
					<tr class="tr">
						<td class="td" colspan="8"><em><br />
								<%:Collecting data...%>
							</em></td>
					</tr>
				</table>
			</div>
		</div>

    </div>
</div>

<!-- Nickname Modal -->
<div id="nicknameModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
    <div style="background-color: white; padding: 30px; border-radius: 8px; text-align: left; width: 450px; display: flex; flex-direction: column; position: relative; box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);">
        <button type="button" onclick="closeModal('nicknameModal')" style="position: absolute; top: 15px; right: 15px; background-color: transparent; border: none; font-size: 24px; color: #666; cursor: pointer; width: 30px; height: 30px; border-radius: 50%; transition: background-color 0.2s;">&times;</button>
        
        <h4 style="margin: 0 0 25px 0; color: #333; font-size: 18px;"><%:Modify Remark%></h4>
        
        <div style="margin-bottom: 20px;">
            <p style="margin: 0 0 8px 0; color: #666; font-size: 14px;"><span class="field-label"><%:MAC Address%>:</span> <span id="nicknameMacDisplay" style="color: #333; font-weight: 500;">--</span></p>
        </div>
        
        <input type="hidden" id="nicknameMac" value="">
        
        <div style="margin-bottom: 30px;">
            <p style="margin: 0 0 8px 0; color: #666; font-size: 14px;"><span class="field-label"><%:Remark%>:</span></p>
            <input type="text" id="nicknameInput" style="padding: 10px; background-color: #f8f9fa; border: 1px solid #ddd; border-radius: 4px; width: 100%; font-size: 14px; transition: border-color 0.2s;" placeholder="请输入备注信息">
        </div>
        
        <div style="display: flex; justify-content: flex-end; gap: 15px; margin-top: 10px;">
            <button type="button" class="cbi-button cbi-button-add" onclick="closeModal('nicknameModal')"><%:Cancel%></button>
            <button type="button" class="cbi-button cbi-button-add" onclick="submitNicknameChange()"><%:OK%></button>
        </div>
    </div>
</div>

<div id="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); z-index: 1000; justify-content: center; align-items: center;">
	<div style="background-color: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px; text-align: center; width: 100px; height: 70px; color: white; display: flex; justify-content: center; align-items: center;">
		<p style="margin: 0;color:white;"><%:Settings saved successfully%></p>
	</div>
</div>
<style>
    .tab-container {
        margin-top: 10px;
    }
    .tab-list {
        display: flex;
        list-style-type: none;
        padding: 0 0 0 10px;
        margin: 0 0 10px 0;
        border-bottom: 1px solid #e0e0e0;
    }
    .tab-item {
        padding: 4px 12px;
        cursor: pointer;
        border: 1px solid #e0e0e0;
        border-bottom: none;
        background-color: #f0f0f0;
        border-radius: 6px 6px 0 0;
        margin-right: 8px;
        transition: all 0.2s ease;
        color: #333;
        font-size: 13px;
    }
    .tab-item.active {
        background-color: white;
        color: rgb(133, 133, 203);
        border-color: #e0e0e0;
        border-bottom: 1px solid white;
        margin-bottom: -1px;
		font-size: 13px;
        z-index: 1;
        position: relative;
    }
    .tab-item:hover {
        background-color: #e0e0e0;
        border-color: #d0d0d0;
    }

	.tab-body {
		margin-top: 5px;
		display: none;
		padding: 25px;
	}
	.tab-body.active {
		
		display: block;
	}

	.pie-chart {
		width: 600px;
	}

	.field-label {
		font-weight: bold;
		color: #333;
		width: 75px; 
		display: inline-block; 
	}
	.field-value {
		color: #4CAF50;
	}
	.info-container {
		display: flex;
		flex-direction: column;
		gap: 10px;
		margin-left: 20px;
	}
	.info-row {
		display: flex;
	}
	.info-column {
		width: 50%;
		text-align: left;
	}
	.info-column p {
		margin-bottom: 20px;
	}

	#user_status_table .td {
		padding-left: 10px !important; /* 5px margin-left + 2px original padding */
	}

	#visit_list_table .td {
		padding: 4px 8px !important; 
		height: 28px !important; 
		vertical-align: middle !important; 
	}

	#visit_list_table .th {
		padding: 6px 8px !important; 
		height: 32px !important; 
		vertical-align: middle !important;
	}

</style>
